
package com.lee.service; 
 
import org.apache.flink.api.common.functions.FlatMapFunction; 
import org.apache.flink.api.java.ExecutionEnvironment; 
import org.apache.flink.api.java.operators.AggregateOperator; 
import org.apache.flink.api.java.operators.DataSource; 
import org.apache.flink.api.java.tuple.Tuple2; 
import org.apache.flink.util.Collector; 
 
public class WordCount { 
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        String inpath = "/data/deploy/20230506/Hello.txt";
 
        DataSource<String> inputData = env.readTextFile(inpath);
        AggregateOperator<Tuple2<String, Integer>> result = inputData.flatMap(new MyFlatMapper()).groupBy(0).sum(1);
        result.print();
 
    }
 
 
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>>{
 
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] words = value.split(" ");
            for(String word:words){
                out.collect(new Tuple2<String,Integer>(word,1));
            }
        }
    }
} 
